#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>

#define MAXLINE 4096
char buf[4096];

struct get_pkg{
		int len;
		char* content;
};

void str_handle(int fd, const char* buf, int n)
{
	int show_buf_size = n - 3;
	char* show_buf = (char*)malloc(show_buf_size);
	memset(show_buf, 0, show_buf_size);
	memcpy(show_buf, buf + 4, show_buf_size - 1);
	show_buf[show_buf_size] = '\0';
	printf("get msg from client: %s", show_buf);
	free(show_buf);
}


int main(int argc, char **argv)
{	
	int listenfd, connfd;
	pid_t childpid;
	socklen_t clien;
	struct sockaddr_in cliaddr, servaddr;

	if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
			printf("creat socket error\n");
			exit(0);
	}

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(6666);

	if(bind(listenfd, (struct sockaddr*) &servaddr, sizeof(servaddr)) == -1) {
			printf("bind socket error: %s(errno: %d)\n", strerror(errno), errno);
			exit(0);
	}

//允许环境变量LISTENQ覆盖调用者指定的值。
	int backlog = atoi("LISTENQ");
	char *ptr;
	if((ptr = getenv("LISTENQ")) != NULL)
			backlog = atoi(ptr);

	if(listen(listenfd, 10) == -1){
			printf("listen socket error\n");
			exit(0);
	}
	

	int n;
	struct get_pkg *pkg;
	for(;;){
			if((connfd = accept(listenfd, NULL, NULL)) == -1) {
				printf("accept socket error\n");
				continue;
			}

			for(;;){	
				if((n = read(connfd, buf, MAXLINE)) == 0){
					printf("recv error\n");
					break;
				} else {
					str_handle(connfd, buf, n);
//					buf[n] = '\0';
//					printf("get mst from client:%s", buf + 4);
				}
			}
	}

	return 0;
}
